import Cookies from "js-cookie";

import {
  getStorageSync,
  setStorageSync,
  removeItem,
  clear
} from "@/utils/storageUtils.js";


var token = "";

var avatar = "";

var userinfo = null;

const TokenKey = "token";


export function getToken() {
  if (token) {
    // console.log("缓存 token")
    return token;
  } else {
    // console.log("初始化 token")
    var user = getUserinfo()
    token = user['token']
    // console.log("==========token:", token)
    return token;
  }
}

/** 获取用户头像 */
export function getAvatar() {
  if (avatar) {
    // console.log("缓存 avatar")
    return avatar;
  } else {
    // console.log("初始化 avatar")
    var user = getUserinfo()
    avatar = user['avatar']
    // console.log("avatar:", avatar)
    return avatar;
  }
}


/** 用户状态 */
export function getUserStatus() {
  var user = getUserinfo()
  // console.log(user, '用户信息')
  if (user) {
    const timestamp = Math.floor(Date.now() / 1000);
    const expiretime = user['expiretime'];
    if (expiretime > timestamp) {
      return true;
    } else {
      return false;
    }

  } else {
    return false;
  }

}


export function setToken(token) {
  return setStorageSync(TokenKey, token);
}

export function removeToken() {
  return removeItem(TokenKey);
}


export function removeUser() {
  // removeItem(TokenKey);
  // removeItem('userinfo');
  userinfo = null;
  token = null;
  removeItem('userinfo')
  // clear()
  return true
}

export function setUserinfo(data) {
  setStorageSync("userinfo", data);
  return;
}

export function getUserinfo() {
  if (userinfo) {
    // console.log('获取缓存用户信息')
    return userinfo;
  }
  // console.log('获取本地用户信息')
  userinfo = getStorageSync("userinfo");
  return userinfo;;
}
